<?php

declare(strict_types=1);

namespace app\start\controller\admin;

use lite\controller\Backend;
use lite\controller\traits\Crud;
use lite\exception\LiteException;
use think\facade\Db;
use app\Request;
use app\start\model\PostImageModel;
use think\Response;

class Post extends Backend
{
    use Crud;

    public function initialize()
    {
        $this->model = new \app\start\model\PostModel();
    }

    /**
     * 查看
     *
     * @return Response
     */
    public function index(Request $request): Response
    {
        if (!empty($request->param('page_size'))) {       // 使用分页
            $list = $this->model->with(['category','images'])->liteFilter()->paginate($request->param('page_size', 10));
        } else {
            $list = $this->model->liteFilter()->select();               // 查询全部
        }

        return success('获取成功', $list);
    }

    /**
     * 详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $detail = $this->model->with('images')->findOrFail($id);
        return success('获取成功', $detail);
    }

    /**
     * 添加
     *
     * @return \think\Response
     */
    public function save(Request $request)
    {
        if (!empty($this->onlyParams)) {                        // 参数过滤
            $params = $request->only($this->onlyParams);
        } else {                                                // 接受全部参数
            $params = $request->param();
        }
        $this->svalidate($params, '.add');

        $result = Db::transaction(function () use ($params) {
            return $this->model->save($params);
        });
        PostImageModel::insertImage($this->model->id,$params['images']);
        if ($result) {
            return success('保存成功', $this->model);
        }
        return error('保存失败');
    }

    /**
     * 编辑(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if (!empty($this->onlyParams)) {                        // 参数过滤
            $params = $request->only($this->onlyParams);
        } else {                                                // 接受全部参数
            $params = $request->param();
        }

        $pk = $this->model->getPk();

        $result = Db::transaction(function () use ($id, $params, $pk) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $params[$pk] = $row->$pk;
                $this->svalidate($params);
                $count += $row->save($params);
            }
            PostImageModel::insertImage($id,$params['images']);
            return $count;
        });

        if ($result) {
            return success('更新成功', $result);
        } else {
            return error('更新失败');
        }
    }
}